# -*- coding: utf-8 -*-
from common.utils import track_logging

from common.utils.decorator import sql_wrapper
from common.utils import db as utils
from common.preset.model.preset import ProfitRate
from common.utils import exceptions as err

_LOGGER = track_logging.getLogger(__name__)


def get_profit_rate_list():
    return ProfitRate.query.filter().all()


def get_profit_rate(preset_id=None, activity_type=None):
    assert preset_id or activity_type

    query = ProfitRate.query.filter()
    if preset_id:
        query = query.filter(ProfitRate.id == preset_id)
    if activity_type:
        query = query.filter(ProfitRate.activity_type == activity_type)

    return query.first()


def check_profit_rate(profit_rate):
    assert isinstance(profit_rate, ProfitRate)
    _LOGGER.info("check_profit_rate {}".format(profit_rate.as_dict()))
    if profit_rate.preset_max_profit_rate < profit_rate.preset_min_profit_rate:
        raise err.DataError(u'抽水上限值小于下限值')

    if not (0 <= profit_rate.preset_max_profit_rate < 1):
        raise err.DataError(u'抽水上限值为[0-1),当前设置{}'.format(profit_rate.preset_max_profit_rate))

    if not (0 <= profit_rate.preset_min_profit_rate < 1):
        raise err.DataError(u'抽水下限值为[0-1),当前设置{}'.format(profit_rate.preset_min_profit_rate))

    if not (0 <= profit_rate.preset_win_rate < 1):
        raise err.DataError(u'抽水生效概率为[0-1),当前设置{}'.format(profit_rate.preset_win_rate))

    if not (0 <= profit_rate.preset_loss_rate < 1):
        raise err.DataError(u'抽水生效概率为[0-1),当前设置{}'.format(profit_rate.preset_loss_rate))


@sql_wrapper
def update_profit_rate(preset_id, preset_amount=None, preset_max_loss=None, preset_max_profit_rate=None,
                       preset_min_profit_rate=None, preset_win_rate=None, preset_loss_rate=None):
    assert preset_id
    _LOGGER.info("update_profit_rate {}, {} ,{} ,{} ,{} ,{} ,{} ".format(preset_id, preset_amount, preset_max_loss,
                                                                         preset_max_profit_rate,
                                                                         preset_min_profit_rate, preset_win_rate,
                                                                         preset_loss_rate))
    profit_rate = ProfitRate.query.filter(ProfitRate.id == preset_id).first()
    if preset_amount is not None:
        profit_rate.preset_amount = preset_amount
    if preset_max_loss is not None:
        profit_rate.preset_max_loss = preset_max_loss
    if preset_max_profit_rate is not None:
        profit_rate.preset_max_profit_rate = preset_max_profit_rate
    if preset_min_profit_rate is not None:
        profit_rate.preset_min_profit_rate = preset_min_profit_rate
    if preset_win_rate is not None:
        profit_rate.preset_win_rate = preset_win_rate
    if preset_loss_rate is not None:
        profit_rate.preset_loss_rate = preset_loss_rate

    check_profit_rate(profit_rate)
    profit_rate.save()
